package com.dreamwhale.machinery.utils;

import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @ClassName : DragonWorkId
 * @Description : 生成验证码和唯一id工具接口
 * @Author : DragonUncle
 * @Date :  9:40 2020/4/28
 */
@Service
public interface WorkIdUtils {


    String str = "0123456789abcdefghijkmnopqrstuvwxyz";

    static String generateRandomCode(Integer value) {
        return generateRandomCode(value, false);
    }

    static String generateRandomCode(Integer value, Boolean letter) {
        return generateRandomCode(value, letter, false);
    }

    static String generateRandomCode(Integer value, Boolean letter, Boolean capsLock) {
        Random random = new Random();
        StringBuilder buffer = new StringBuilder();
        for (Integer i = 0; i < value; i++) {
            if (letter) {
                int length = str.length();
                int anInt = random.nextInt(length);
                String substring = str.substring(anInt, anInt + 1);
                if (anInt % 2 == 0 && capsLock) {
                    buffer.append(substring.toUpperCase());
                } else {
                    buffer.append(substring.toLowerCase());
                }
            } else {
                buffer.append(random.nextInt(10));
            }
        }
        return buffer.toString();
    }

    static String generateOrderId() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmsss");
        String format = simpleDateFormat.format(new Date());
        return format + generateRandomCode(6);
    }

    static Map<String, Object> entityToMap(Object object) {
        if (object == null) return new HashMap<>();
        Class aClass = object.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        Map<String, Object> map = new HashMap<>();
        for (Field declaredField : declaredFields) {
            try {
                declaredField.setAccessible(true);
                map.put(declaredField.getName(), declaredField.get(object));
            } catch (IllegalAccessException e) {
                map.put(declaredField.getName(), null);
            }
        }
        return map;
    }
}
